package com.yuntsg.nnsfcp.common.aop;


import com.yuntsg.nnsfcp.front.entity.SysLog;
import com.yuntsg.nnsfcp.front.mapper.SysLogMapper;
import com.yuntsg.nnsfcp.util.IpAddressUtil;
import com.yuntsg.nnsfcp.util.Operation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.time.LocalDate;

@Aspect
@Component
public class SysLogAspect {
    /*
     * 2019年8月2日17:30:19 用于记录用户log操作日志
     * */

    @Resource
    HttpSession session;
    @Resource
    private SysLogMapper sysLogMapper;

    @Pointcut("@annotation(com.yuntsg.nnsfcp.util.Operation)")
    public void logPoinCut() {

    }


    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint) {

        SysLog sysLog = new SysLog();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();
//        String targetName = joinPoint.getTarget().getClass().getName();
//        String methodName = joinPoint.getSignature().getName();//目标方法名
//        System.out.println(targetName);
//        System.out.println(methodName);

        //获取操作
        Operation operation = method.getAnnotation(Operation.class);
        if (operation != null) {
            String value = operation.value();
            sysLog.setOperation(value);//保存获取的操作
        }
        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName1 = method.getName();
        sysLog.setMethod(className + "." + methodName1);
        //请求的参数
//        Object[] args = joinPoint.getArgs();
        //将参数所在的数组转换成json
//        String params = null;
//        try {
//            //params = JacksonUtil.obj2json(args);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        //请求的时间
        sysLog.setAddtime(LocalDate.now());
        //获取用户名
        String username = session.getAttribute("username") == null ? "超级管理员测试" : session.getAttribute("username").toString();
        sysLog.setUsername(username);
        //获取用户ip地址
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        sysLog.setIp(IpAddressUtil.getIpAddress(request));
        sysLogMapper.insert(sysLog);
    }


}
